package com.atlin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.atlin.exception.CustomException;
import com.atlin.license.LicenseCreator;
import com.atlin.model.LicenseCheckModel;
import com.atlin.model.LicenseCreatorParam;
import com.atlin.model.ServerInfoModel;
import com.atlin.model.params.LicenseParams;
import com.atlin.service.LicenseService;
import com.atlin.util.SM4Encryptor;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * license服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LicenseServiceImpl implements LicenseService {


    @Override
    public void generateLicense(MultipartFile file, LicenseParams licenseParams, HttpServletResponse response) {
        if (file == null || file.isEmpty()) {
            throw new CustomException("文件数据不存在");
        }

        try {
            String encryptedMsg = new String(file.getBytes(), StandardCharsets.UTF_8);
            if (StringUtils.isBlank(encryptedMsg)) {
                throw new CustomException("客户端指纹数据为空");
            }
            String content = SM4Encryptor.decryptCBC(encryptedMsg);
            ServerInfoModel serverInfoModel = JSONUtil.toBean(content, ServerInfoModel.class);
            serverInfoModel.valid();
            serverInfoModel.setIpAddress(serverInfoModel.getIpAddress().stream().sorted().toList());
            serverInfoModel.setMacAddress(serverInfoModel.getMacAddress().stream().sorted().toList());

            LicenseCheckModel licenseCheckModel = BeanUtil.copyProperties(serverInfoModel, LicenseCheckModel.class);
            LicenseCreator licenseCreator = new LicenseCreator(buildCreatorParam(licenseCheckModel, licenseParams));

            byte[] bytes = licenseCreator.generateLicense();
            String fileName = URLEncoder.encode("license.lic", StandardCharsets.UTF_8);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            response.setContentLength(bytes.length);

            try (OutputStream os = response.getOutputStream()) {
                os.write(bytes);
                os.flush();
            }
        } catch (Exception e) {
            log.error("生成许可文件失败", e);
            throw new CustomException("生成许可文件失败: " + e.getMessage());
        }
    }

    public LicenseCreatorParam buildCreatorParam(LicenseCheckModel licenseCheckModel, LicenseParams licenseParams) {
        LicenseCreatorParam creatorParam = new LicenseCreatorParam();
        creatorParam.setSubject("地震监测预报服务平台使用授权许可");
        creatorParam.setPrivateAlias("privateKey");
        creatorParam.setKeyPass("private_password1234");
        creatorParam.setStorePass("public_password1234");
//        creatorParam.setLicensePath("/wykj/code/ers/temp/license/license.lic");
        creatorParam.setLicensePath("/temp/license/license.lic");
//        creatorParam.setPrivateKeysStorePath("/wykj/code/ers/temp/license/privateKeys.keystore");
        creatorParam.setPrivateKeysStorePath("D:/wykj/code/ers/temp/license/privateKeys.keystore");
        creatorParam.setExpiryTime(licenseParams.getExpiryTime());
//        creatorParam.setExpiryTime(DateUtil.parse("2025-11-21 23:59:59"));
//        licenseCheckModel.setRoutePath(Arrays.asList("/auth/login", "/auth/post", "/auth/get"));
        licenseCheckModel.setRoutePath(licenseParams.getRoutePath());

        creatorParam.setLicenseCheckModel(licenseCheckModel);

        return creatorParam;
    }

}
